import { Notes } from '@entities/Notes'
import { yupResolver } from '@hookform/resolvers/yup'
import { useCreateNoteMutation } from '@shared/api'
import { useAppSelector } from '@shared/lib/hooks/redux'
import { useClosePopup } from '@shared/lib/hooks/useClosePopup'
import { Button } from '@shared/ui/Button'
import { CustomInput } from '@shared/ui/CustomInput'
import { FieldError } from '@shared/ui/FieldError'
import { Panel } from '@shared/ui/Panel'
import { TextArea } from '@shared/ui/TextArea'
import { Title } from '@shared/ui/Title'
import moment from 'moment'
import { useForm } from 'react-hook-form'
import { AddNotesSchema } from '../model/AddNotesScheme'
import styles from './AddNotesForm.module.scss'

interface AddNotesForm {
  id?: string | undefined
  text: string
  title: string
}

interface AddNotesFormProps {
  notes?: Notes
}

export const AddNotesForm = ({ notes }: AddNotesFormProps) => {
  const closeNotesForm = useClosePopup()
  const [createNotesItem] = useCreateNoteMutation()
  const userId = useAppSelector((state) => state.user.id)
  const dueCreateDate = moment(notes?.createDate) ?? moment()

  const {
    formState: { errors, isValid },
    handleSubmit,
    register,
  } = useForm<AddNotesForm>({
    mode: 'onChange',
    resolver: yupResolver(AddNotesSchema),
  })

  const onSubmit = async (data: AddNotesForm) => {
    const { ...note } = data
    console.log(data)
    const noteRequest: Notes = {
      ...(note as Notes),
      createDate: dueCreateDate,
      ...(userId && { userId }),
    }
    await createNotesItem(noteRequest)
    closeNotesForm()
  }

  return (
    <Panel className={styles.component}>
      <Title center tag='h2'>
        Новая заметка
      </Title>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div>
          <CustomInput
            className={styles.input}
            name='title'
            placeholder='Название проекта...'
            register={register('title')}
            type='text'
          />
          <FieldError>{errors.title?.message}</FieldError>
        </div>
        <TextArea
          name='text'
          placeholder='Описание'
          register={register('text')}
          type='text'
        ></TextArea>
        <div className={styles.wrapper}>
          <Button color='success' disabled={!isValid} size='small' type='submit'>
            Создать
          </Button>
          <Button color='error' onClick={closeNotesForm} size='small'>
            Отменить
          </Button>
        </div>
      </form>
    </Panel>
  )
}
